'use client';

import { useState } from 'react';
import { 
  User, 
  Mail, 
  Edit2, 
  Save,
  X,
  Hash
} from 'lucide-react';
import { useSession } from '@/lib/auth-client';
import { useToast } from '@/components/ui/ToastProvider';

interface ProfilePageProps {
  params: { userId: string };
}

export default function ProfilePage({ params: { userId } }: ProfilePageProps) {
  const { data: session } = useSession();
  const { showSuccess, showError } = useToast();
  const [isEditingName, setIsEditingName] = useState(false);
  const [editedName, setEditedName] = useState(session?.user?.name || '');
  const [isSaving, setIsSaving] = useState(false);

  // 如果没有用户session，显示加载状态
  if (!session?.user) {
    return (
      <div className="flex items-center justify-center min-h-64">
        <div className="text-center">
          <div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-2"></div>
          <p className="text-muted-foreground">加载用户信息中...</p>
        </div>
      </div>
    );
  }

  const user = session.user;

    // 处理保存用户名
  const handleSaveName = async () => {
    if (!editedName.trim()) {
      showError('错误', '用户名不能为空');
      return;
    }

    setIsSaving(true);
    try {
      const response = await fetch('/api/user/update-name', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name: editedName.trim() }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '更新失败');
      }
      
      setIsEditingName(false);
      showSuccess('成功', '用户名已更新');
      
      // 刷新页面来获取最新的用户信息
      window.location.reload();
    } catch (error) {
      console.error('更新用户名失败:', error);
      showError('错误', error instanceof Error ? error.message : '更新用户名失败，请重试');
    } finally {
      setIsSaving(false);
    }
  };

  // 取消编辑
  const handleCancelEdit = () => {
    setEditedName(user.name || '');
    setIsEditingName(false);
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div>
        <h1 className="text-3xl font-bold text-foreground">账号信息</h1>
        <p className="text-muted-foreground mt-1">管理您的个人资料</p>
      </div>

      {/* 用户信息卡片 */}
      <div className="bg-card rounded-xl p-8 border shadow-sm">
        <div className="flex items-start space-x-6">
          {/* 用户头像 */}
          <div className="relative">
            <div className="w-20 h-20 bg-primary rounded-xl flex items-center justify-center shadow-lg">
              <span className="text-primary-foreground font-bold text-2xl">
                {(user.name || user.email)?.charAt(0).toUpperCase()}
              </span>
            </div>
            <div className="absolute -bottom-1 -right-1 w-5 h-5 bg-green-500 rounded-full border-2 border-white dark:border-slate-800"></div>
          </div>

          {/* 用户信息 */}
          <div className="flex-1 space-y-6">
            {/* 用户名编辑区域 */}
            <div className="space-y-2">
              <label className="flex items-center space-x-2 text-sm font-medium text-muted-foreground">
                <User className="w-4 h-4" />
                <span>用户名</span>
              </label>
              {isEditingName ? (
                <div className="flex items-center space-x-2">
                  <input
                    type="text"
                    value={editedName}
                    onChange={(e) => setEditedName(e.target.value)}
                    className="flex-1 px-3 py-2 border border-input rounded-lg bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                    placeholder="请输入用户名"
                    disabled={isSaving}
                  />
                  <button
                    onClick={handleSaveName}
                    disabled={isSaving}
                    className="px-3 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-1"
                  >
                    {isSaving ? (
                      <div className="w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"></div>
                    ) : (
                      <Save className="w-4 h-4" />
                    )}
                  </button>
                  <button
                    onClick={handleCancelEdit}
                    disabled={isSaving}
                    className="px-3 py-2 border border-input rounded-lg hover:bg-accent transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>
              ) : (
                <div className="flex items-center space-x-2">
                  <span className="text-lg font-medium text-foreground flex-1">
                    {user.name || '未设置用户名'}
                  </span>
                  <button
                    onClick={() => setIsEditingName(true)}
                    className="px-3 py-1 text-sm bg-primary/10 text-primary rounded-lg hover:bg-primary/20 transition-colors flex items-center space-x-1"
                  >
                    <Edit2 className="w-3 h-3" />
                    <span>编辑</span>
                  </button>
                </div>
              )}
            </div>

            {/* 用户ID */}
            <div className="space-y-2">
              <label className="flex items-center space-x-2 text-sm font-medium text-muted-foreground">
                <Hash className="w-4 h-4" />
                <span>用户ID</span>
              </label>
              <div className="flex items-center space-x-2">
                <span className="text-lg font-mono text-foreground bg-muted px-3 py-2 rounded-lg">
                  {user.id}
                </span>
                <span className="text-xs text-muted-foreground">
                  (此ID无法修改)
                </span>
              </div>
            </div>

            {/* 邮箱 */}
            <div className="space-y-2">
              <label className="flex items-center space-x-2 text-sm font-medium text-muted-foreground">
                <Mail className="w-4 h-4" />
                <span>邮箱地址</span>
              </label>
              <div className="flex items-center space-x-2">
                <span className="text-lg text-foreground">
                  {user.email}
                </span>
                {user.emailVerified && (
                  <span className="inline-flex items-center px-2 py-1 bg-green-100 dark:bg-green-900/20 text-green-800 dark:text-green-400 text-xs font-medium rounded-full">
                    已验证
                  </span>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 账户状态信息 */}
      <div className="bg-card rounded-xl p-6 border shadow-sm">
        <h3 className="text-lg font-semibold text-foreground mb-4">账户状态</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <h4 className="text-sm font-medium text-muted-foreground mb-1">账户创建时间</h4>
            <p className="text-sm text-foreground">
              {user.createdAt ? new Date(user.createdAt).toLocaleDateString('zh-CN') : '未知'}
            </p>
          </div>
                     <div>
             <h4 className="text-sm font-medium text-muted-foreground mb-1">账户类型</h4>
             <span className="inline-flex items-center px-2 py-1 bg-primary/10 text-primary text-xs font-medium rounded-full">
               普通用户
             </span>
           </div>
        </div>
      </div>
    </div>
  );
} 